package com.dwork.base.mybatis.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class CalendarTypeHandler extends BaseTypeHandler<Calendar> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i,
			Calendar parameter, JdbcType jdbcType) throws SQLException {
		ps.setDate(i, new java.sql.Date((parameter.getTime().getTime())),parameter);
	}

	@Override
	public Calendar getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		java.sql.Date sqlDate = rs.getDate(columnName);
		if (sqlDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new java.util.Date(sqlDate.getTime()));
			return calendar;
		}
		return null;
	}

	@Override
	public Calendar getNullableResult(ResultSet rs, int columnIndex)
			throws SQLException {
		java.sql.Date sqlDate = rs.getDate(columnIndex);
		if (sqlDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new java.util.Date(sqlDate.getTime()));
			return calendar;
		}
		return null;
	}

	@Override
	public Calendar getNullableResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		java.sql.Date sqlDate = cs.getDate(columnIndex);
		if (sqlDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new java.util.Date(sqlDate.getTime()));
			return calendar;
		}
		return null;
	}

}
